package cn.seaboot.admin.video;

import cn.seaboot.commons.file.IOUtils;
import cn.seaboot.commons.file.ResponseWriter;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 视频分段写出 demo
 */
@Controller
@RequestMapping("sys/video")
public class VideoStreamController {

    private static final String VIDEO_PATH = "C:\\Download\\1756861375932.mpeg"; // 替换为你的MP4路径

    @RequestMapping(value = "range.mpeg", method = RequestMethod.GET)
    public void streamVideo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Path videoPath = Paths.get(VIDEO_PATH);
        Resource resource = new UrlResource(videoPath.toUri());
        long fileSize = resource.contentLength();

        String range = request.getHeader("Range");

        System.out.println("rangeHeader: " + range);
        System.out.println("fileSize: " + fileSize);

        if (range == null || "null".equals(range)) {
            // 无 Range 请求，返回整个文件（不推荐大文件）
            try(InputStream in = resource.getInputStream(); OutputStream out = response.getOutputStream()){
                response.setContentType("video/mpeg");
                response.setContentLength((int) fileSize);
                response.setHeader("Content-Disposition", "attachment; filename=\"" + resource.getFilename() + "\"");

                    IOUtils.copy(in, out);
            }
        } else {
            ResponseWriter.writeRange(response, range, new File(VIDEO_PATH));
        }
    }
}